<?php

App::import('Sanitize');

class SetupsController extends AppController {

    var $name = 'Setups';
    var $helpers = array('Html', 'Session');
    var $uses = array('User');
    var $components = array('Auth');

    function beforeFilter() {
        $this->Auth->fields = array(
            'username' => 'username',
            'password' => 'password'
        );
        $this->Auth->allow(array('admin_login', 'admin_logout', 'admin_get_attributes_cat'));
        $this->Auth->loginRedirect = array('controller' => 'Setups', 'action' => 'admin_dashboard');
        $this->Auth->logoutRedirect = array('controller' => 'Setups', 'action' => 'admin_login');
        $this->Auth->loginError = "You are not authorised!";
        $this->Auth->authError = "Sorry, you are lacking access.";
        parent::beforeFilter();
    }

    /*     * ********************************************************************************************************************************** */
    /*     * ****************************************************Admin Dashboard	****************************************************************************** */

    function admin_dashboard() {
        echo __METHOD__;
        $this->layout = 'admin';

        $top_sellers = $this->Order->query("SELECT seller_id, count( seller_id ) AS count
											FROM order_items
											GROUP BY seller_id
											HAVING Count( seller_id ) >1
											OR count( seller_id ) =1
											ORDER BY count Desc
											LIMIT 0 , 10 ");
        foreach ($top_sellers as $top_selle_id) {
            $seller = $this->Seller->findById($top_selle_id['order_items']['seller_id']);
            $top_seller[] = $seller;
        }
        if (isset($top_seller) and ($top_seller)) {
            $this->Set('top_seller', $top_seller);
        }


        $top_products = $this->Order->query("SELECT product_id,seller_id,  count( product_id ) AS count
											FROM order_items
											GROUP BY product_id
											HAVING Count( product_id ) >1
											OR count(product_id) =1
											ORDER BY count Desc
											LIMIT 0 , 10 ");
        foreach ($top_products as $product_id) {
            $product_details = $this->Product->findById($product_id['order_items']['product_id']);
            if (isset($product_details) and ($product_details)) {
                $category = $this->Category->findById($product_details['Product']['cat_id']);

                $product_details['Product']['category'] = $category['Category'];

                $stock_detail = $this->_get_stock_position($product_details['Product']['stock']);

                $product_details['Product']['stock_detail'] = $stock_detail;

                $MasterProduct = $this->__getPaid_product_min_price($product_details['Product']['id'], $product_id['order_items']['seller_id']);

                $seller = $this->_get_seller($MasterProduct['seller_id']);

                $MasterProduct['Seller'] = $seller['Seller'];

                $product_details['Product']['MasterProduct'] = $MasterProduct;

                $brand_name = $this->_get_brand_name($product_details['Product']['brand_id']);

                $product_details['Product']['Brand'] = $brand_name;

                $ratings = $this->__get_product_rating($product_details['Product']['wisn']);

                $product_details['Product']['rating'] = $ratings;

                $product_price_offers = $this->__product_price_list($product_details['Product']['id']);

                $product_details['Product']['offers'] = $product_price_offers;
                $products[] = $product_details;
            }
        }
        if (isset($products) and ($products)) {
            $this->Set('products', $products);
        }

        $total_sales_dates = $this->Order->query("SELECT DISTINCT created FROM `orders` where payment_status='1' order By created DESC");
        $x = 0;
        foreach ($total_sales_dates as $dates) {
            $orders_total_sales = $this->Order->find('all', array('conditions' => 'Order.created="' . $dates['orders']['created'] . '" and Order.payment_status="1"',
                'fields' => 'Order.total_price, Order.wondere_price,Order.selllers_prices,Order.payment_method'));
            $total_price = 0;
            $wondere_price = 0;
            $k = 0;
            foreach ($orders_total_sales as $sale) {
                $total_price = $total_price + $sale['Order']['total_price'];
                $wondere_price = $wondere_price + $sale['Order']['wondere_price'];
                $k++;
            }
            $orders_total_sales['sp']['total_price'] = $total_price;
            $orders_total_sales['sp']['payment_method'] = $sale['Order']['payment_method'];
            $orders_total_sales['sp']['wondere_price'] = $wondere_price;

            $order[$x]['date'] = $dates['orders']['created'];
            $order[$x]['states'] = $orders_total_sales['sp'];

            $x++;
        }

        if (isset($order) and ($order)) {
            //pr($order);
            //exit;
            $this->Set('total_orders', $order);
        }
    }

    function admin_index() {
        echo __METHOD__;
        $this->layout = 'admin';
        $this->redirect(array('action' => 'admin_dashboard', 'admin' => true));
    }

    /*     * ****************************************************** Admin Logout**************************************************************************** */

    function admin_logout() {
        echo __METHOD__;
        $date = date('Y-m-d h:i:s');
        $userid = $this->Auth->User('id');
        $this->User->updateAll(array('User.last_login' => "'" . $date . "'"), array('User.id' => $userid));
        $this->Session->destroy('user');
        $this->Session->setFlash('You\'ve successfully logged out.');
        $this->redirect($this->Auth->logout());
    }

    /*     * **************************************************************Admin Login******************************************************************** */

    function admin_login() {
        echo __METHOD__;
        $this->layout = "admin_login";
        $this->Auth->login($this->data);
        $is_admin = $this->Auth->User('is_admin');
        if (isset($is_admin) and ($is_admin)) {
            $this->redirect(array('controller' => 'Setups', 'action' => 'dashboard'));
        }
    }

    /*     * ******************************************************** User Management************************************************************************** */

    function admin_users_list($role="") {
        echo __METHOD__;
        if (isset($role) and ($role)) {
            $condition = "User.role='" . $role . "'";
            $this->Set('role', $role);
        } else {
            $role = "";
            $condition = "";
        }
        isset($this->data['User']) ? $sort = $this->data['User'] : $sort = "id ASC";
        $this->paginate['User'] = array('conditions' => $condition,
            'order' => "$sort",
            'fields' => array('User.*')
        );
        $user_list = $this->paginate('User');
        $i = 0;
        $this->set('user_list', $user_list);
    }

    function admin_sellers_list() {
        echo __METHOD__;
        isset($this->data['Seller']) ? $sort = $this->data['Seller'] : $sort = "id ASC";
        $this->paginate['Seller'] = array('conditions' => '',
            'order' => "$sort",
            'fields' => array('Seller.*')
        );
        $Seller_list = $this->paginate('Seller');
        $x = 0;
        foreach ($Seller_list as $Seller) {
            $user = $this->User->findById($Seller['Seller']['user_id']);
            $Seller_list[$x]['Seller']['User'] = $user['User'];
            $x++;
        }
        $this->set('Seller_list', $Seller_list);
    }

    function admin_edit_seller($id="") {
        echo __METHOD__;
        $user_details = $this->Seller->findById($id);
        if (isset($user_details) and ($user_details)) {
            $this->set('details', $user_details);
        }

        if (empty($this->data) == false) {
            if ($this->data) {
                if (isset($this->data['Seller']) and ($this->data['Seller'])) {
                    $this->Seller->Save($this->data['Seller']);
                }
                $this->Session->setFlash('Data Has been Successfully Saved.');
                $this->redirect(array('controller' => 'Setups', 'action' => 'admin_sellers_list'));
            }
        }
    }

    function admin_orders($type="") {
        echo __METHOD__;
        if (isset($type) and ($type)) {
            if ($type == 'recent') {
                $last_7_days = $this->_last_dates(7, 'd');
                $conditions = "Order.payment_status = '1' and Order.created<='" . date('Y-m-d') . "' and Order.created>='" . $last_7_days . "'";
            } elseif ($type == 'paid') {
                $conditions = "Order.payment_status = '1'";
            } elseif ($type == 'unpaid') {
                $conditions = "Order.payment_status = '0'";
            }
            $this->Set('type', $type);
        } else {
            $type = "";
        }
        isset($this->data['Order']) ? $sort = $this->data['Order'] : $sort = "Order.id ASC";
        $this->paginate['Order'] = array('conditions' => $conditions,
            'limit' => 10,
            'order' => "$sort",
        );
        $Order_list = $this->paginate('Order');
        //pr($Order_list);
        //exit;
        $i = 0;
        $this->set('Order_list', $Order_list);
    }

    function admin_orders_finaces() {
        echo __METHOD__;
        $type = 'paid';
        if (isset($type) and ($type)) {
            if ($type == 'recent') {
                $last_7_days = $this->_last_dates(7, 'd');
                $conditions = "Order.payment_status = '1' and Order.created<='" . date('Y-m-d') . "' and Order.created>='" . $last_7_days . "'";
            } elseif ($type == 'paid') {
                $conditions = "Order.payment_status = '1'";
            } elseif ($type == 'unpaid') {
                $conditions = "Order.payment_status = '0'";
            }
            $this->Set('type', $type);
        } else {
            $type = "";
        }
        isset($this->data['Order']) ? $sort = $this->data['Order'] : $sort = "Order.id ASC";
        $this->paginate['Order'] = array('conditions' => $conditions,
            'limit' => 10,
            'order' => "$sort",
        );
        $Order_list = $this->paginate('Order');
        //pr($Order_list);
        //exit;
        $i = 0;
        $this->set('Order_list', $Order_list);
    }

    function admin_order_details() {
        echo __METHOD__;
        $orderTrackingId = $this->params['named']['order_id'];
        $orderItems = $this->OrderItem->find('all', array('conditions' => 'OrderItem.order_tracking_id="' . $orderTrackingId . '"'));
        $x = 0;
        foreach ($orderItems as $orderItem) {
            $order = $this->Order->findByTrackingId($orderItem['OrderItem']['order_tracking_id']);
            $orderItems[$x]['Order'] = $order['Order'];
            $products = $this->_getMerchantProduct('Product.id="' . $orderItem['OrderItem']['product_id'] . '"', $orderItem['OrderItem']['seller_id']);
            $orderItems[$x]['OrderItem']['Product'] = $products[0]['Product'];
            $seller = $this->Seller->findById($orderItem['OrderItem']['seller_id']);
            $orderItems[$x]['OrderItem']['Seller'] = $seller['Seller'];
            $x++;
        }
        //pr($orderItems);
        //exit;
        $this->set('orderItems', $orderItems);
    }

    function admin_order_pay($order_id="", $order_item_id="", $order_item_bank_code="") {
        echo __METHOD__;
        $this->Set('order_id', $order_id);
        $this->Set('order_item_id', $order_item_id);
        $this->Set('order_item_bank_code', $order_item_bank_code);
        if (isset($this->data['OrderItem']) and ($this->data['OrderItem'])) {
            //pr($this->data);
            //exit;
            if (isset($this->data['OrderItem']['bank_code']) and ($this->data['OrderItem']['bank_code'])) {
                $bank_code = "" . $this->data['OrderItem']['bank_code'] . "";
                $this->Session->setFlash('Merchant Bank Code has been Added');
            } else {
                $bank_code = "";
                $this->Session->setFlash('Merchant Bank Code has been Deleted');
            }
            $this->OrderItem->updateAll(
                    array('OrderItem.bank_code' => "'" . $bank_code . "'"), array('OrderItem.order_Item_Id' => $this->data['OrderItem']['order_Item_Id'])
            );

            $this->redirect(array('action' => 'orders_finaces'));
        }
    }

    /*
     * Feb 24 2012 Start
     */

    function admin_attribute_groups() {
        echo __METHOD__;
        $attrGroups = $this->AttrGroup->find('all');
        $x = 0;
        foreach ($attrGroups as $attrGroup) {
            $category = $this->__get_details($attrGroup['AttrGroup']['cat_id'], 'Category');
            $attrGroups[$x]['AttrGroup']['Category'] = $category['Category']['name'];
            $x++;
        }
        //pr($attrGroups);
        //exit;
        $this->Set('attrGroups', $attrGroups);
    }

    function admin_add_attr_group($model ="", $enc_id="") {
        echo __METHOD__;
        $_list_categories = $this->_list_categories();
        $cat_keys = array_keys($_list_categories);

        $x = 0;
        foreach ($cat_keys as $cat_id) {
            $cat_name = $this->Category->findById($cat_id, array('fields' => 'Category.name'));

            $_list_categori[$x]['subcatecategories'] = $this->_get_subcatecategories($cat_id);
            if (isset($_list_categori[$x]['subcatecategories']) and ($_list_categori[$x]['subcatecategories'])) {
                $_list_categori[$x]['name'] = $cat_name['Category']['name'];
            }
            $x++;
        }
        $this->Set('_list_categories', $_list_categori);

        if (isset($enc_id) and ($enc_id)) {
            $dec_id = base64_decode($enc_id);

            $details = $this->AttrGroup->findById($dec_id);
            $this->Set('details', $details);
        }



        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['AttrGroup']) and ($this->data['AttrGroup'])) {
                //pr($this->data['AttrGroup']);
                //exit;
                $this->AttrGroup->Save($this->data['AttrGroup']);
                $this->redirect(array('action' => 'admin_attribute_groups'));
            }
        }
    }

    function admin_attributes() {
        echo __METHOD__;
        $attrGroups = $this->Attribute->find('all');
        $x = 0;
        foreach ($attrGroups as $attrGroup) {
            $attrGroupD = $this->__get_detils($attrGroup['Attribute']['attr_gp_id'], 'AttrGroup');
            $attrGroups[$x]['Attribute']['GroupName'] = $attrGroupD['AttrGroup']['name'];
            $x++;
        }
        $this->Set('Attributes', $attrGroups);
    }

    function admin_add_attr($model ="", $enc_id="") {
        echo __METHOD__;
        if (isset($enc_id) and ($enc_id)) {
            $dec_id = base64_decode($enc_id);
            $details = $this->Attribute->findById($dec_id);
            $this->Set('details', $details);
        }
        $att_groups = $this->__list_attr_groups();
        $this->Set('att_groups', $att_groups);

        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['Attribute']) and ($this->data['Attribute'])) {
                $this->Attribute->Save($this->data['Attribute']);
                $this->redirect(array('action' => 'admin_attributes'));
            }
        }
    }

    function admin_options() {
        echo __METHOD__;
        $Options = $this->Option->find('all');
        $this->Set('Options', $Options);
    }

    function admin_add_option($model ="", $enc_id="") {
        echo __METHOD__;
        if (isset($enc_id) and ($enc_id)) {
            $dec_id = base64_decode($enc_id);

            $details = $this->Option->findById($dec_id);
            $this->Set('details', $details);
        }

        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['Option']) and ($this->data['Option'])) {
                $this->Option->Save($this->data['Option']);
                $this->redirect(array('action' => 'admin_options'));
            }
        }
    }

    function admin_option_values($option_id="") {
        echo __METHOD__;
        $option_values = $this->OptionValue->find('all');
        $x = 0;
        foreach ($option_values as $option) {
            $option = $this->Option->findById($option['OptionValue']['option_id']);
            $option_values[$x]['OptionValue']['Optionname'] = $option['Option']['name'];
            $x++;
        }
        //pr($option_values);
        //exit;
        $this->Set("OptionValues", $option_values);
    }

    function admin_add_optionvalue($model ="", $enc_id="") {
        echo __METHOD__;
        $__list_options = $this->__list_options();
        //pr($__list_options);
        //exit;
        $this->Set('list_options', $__list_options);

        if (isset($enc_id) and ($enc_id)) {
            $dec_id = base64_decode($enc_id);
            $details = $this->OptionValue->findById($dec_id);
            $this->Set('details', $details);
        }

        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['OptionValue']) and ($this->data['OptionValue'])) {
                foreach ($this->data['OptionValue'] as $optionvalue) {
                    $this->data['OptionValue']['id'] = "";
                    $this->data['OptionValue']['value_name'] = $optionvalue['name'];
                    $this->data['OptionValue']['option_id'] = $optionvalue['option_id'];
                    $this->data['OptionValue']['status'] = $optionvalue['status'];
                    $this->OptionValue->Save($this->data['OptionValue']);
                }
                $this->redirect(array('action' => 'admin_option_values'));
            }
        }
    }

    function admin_brands() {
        echo __METHOD__;
        $brands = $this->_get_brands(30, "Brand.id Desc");
        $this->Set('brands', $brands);
    }

    function admin_get_brands_values() {
        echo __METHOD__;
        $this->layout = "ajax";
        $params = $this->params;
        if (isset($params['form']['cat_id']) and ($params['form']['cat_id'])) {
            $cat_id = $params['form']['cat_id'];
            $brands = $this->Brand->find('all', array('conditions' => 'Brand.cat_id Like "%' . $cat_id . '%"'));
            if (isset($brands) and ($brands)) {
                //pr($brands);
                //exit;
                echo '<select id="ProductBrandId" class="mws-textinput" name="data[Product][brand_id]">';
                foreach ($brands as $brand) {
                    //pr($brand);
                    //exit;
                    echo '
										<option value="' . $brand['Brand']['id'] . '">' . $brand['Brand']['name'] . '</option>
									     ';
                }
                echo '</select>';
            } else {
                echo '<select id="ProductBrandId" class="mws-textinput" name="data[Product][brand_id]">';
                echo '
										<option value="">No Brads</option>
									     ';
                echo '</select>';
            }
        }
        exit;
    }

    function admin_adduploadproduct() {

        echo __METHOD__;
        $current_directory = getcwd();
        require_once($current_directory . '/../vendors/parsecsv/parsecsv.lib.php');
        $csv = new parseCSV();
        if (isset($this->data['Product']['uploadinventory']) and ($this->data['Product']['uploadinventory'])) {
            //pr($this->data);
            $csv->auto($this->data['Product']['uploadinventory']['tmp_name']);
            $data = $csv->data;
            $user_id = $this->Auth->User('id');
            $seller_id = $this->Seller->findByUserId($user_id, array('fields' => 'Seller.id'));
            //pr( $seller_id);
            //exit;
            $seller_id_1 = $seller_id['Seller']['id'];
            $c = 0;
            foreach ($data as $mydata) {
                $x = 0;
                foreach ($mydata as $key => $value) {
                    $key = explode('-', $key);
                    $key = $key[0];
                    //echo $key."<br>";
                    $keyLetter = explode(':', $key);
                    $keyLetterKey = $keyLetter[0];
                    if (isset($keyLetter[1]) and ($keyLetter[1])) {
                        if ($keyLetterKey == 'M') {
                            $keyname = str_replace(" ", "", $keyLetter[1]);
                            if (isset($keyname) and ($keyname == 'price')) {
                                $Product[$c]['MasterProduct']['' . $keyname . ''] = str_replace(",", "", $value);
                            } else {
                                $Product[$c]['MasterProduct']['' . $keyname . ''] = $value;
                            }
                        } else {
                            $keyname = str_replace(" ", "", $keyLetter[1]);
                            if (isset($keyname) and ($keyname == 'cat_id')) {
                                $cat_id = $this->Category->findByName($value, array('fields' => 'Category.id'));
                                if (isset($cat_id) and ($cat_id)):
                                    $Product[$c]['Product']['' . $keyname . ''] = $cat_id['Category']['id'];
                                endif;
                            }
                            elseif (isset($keyname) and ($keyname == 'msrp')) {
                                $Product[$c]['Product']['' . $keyname . ''] = str_replace(",", "", $value);
                            } elseif (isset($keyname) and ($keyname == 'parent_cat_id')) {
                                $cat_id = $this->Category->findByName($value, array('fields' => 'Category.id'));
                                if (isset($cat_id) and ($cat_id)):
                                    $Product[$c]['Product']['' . $keyname . ''] = $cat_id['Category']['id'];
                                endif;
                            }
                            elseif (isset($keyname) and ($keyname == 'brand_id')) {
                                $Brand_id = $this->Brand->findByName($value, array('fields' => 'Brand.id'));
                                if (isset($Brand_id) and ($Brand_id)):
                                    $Product[$c]['Product']['' . $keyname . ''] = $Brand_id['Brand']['id'];
                                endif;
                            }
                            elseif (isset($keyname) and ($keyname == 'dept_id')) {
                                $Department_id = $this->Department->findByName($value, array('fields' => 'Department.id'));
                                if (isset($Department_id) and ($Department_id)) {
                                    $Product[$c]['Product']['' . $keyname . ''] = $Department_id['Department']['id'];
                                } else {
                                    unset($Product[$c]['Product']['' . $keyname . '']);
                                }
                            } else {
                                $Product[$c]['Product']['' . $keyname . ''] = $value;
                            }
                        }
                    }
                    $x++;
                }
                $c++;
            }
            if (isset($Product) and ($Product)) {
                $no = 1;
                foreach ($Product as $Productno) {
                    /* echo $no; */
                    if (isset($Productno['Product']['name']) and ($Productno['Product']['name'])):
                        $this->data['Product'] = $Productno['Product'];
                        $this->data['Product']['id'] = "";
                        $this->data['Product']['upload'] = "1";
                        $slug = str_replace(" ", "_", $this->data['Product']['name']);
                        $slug = strtolower($slug);
                        $this->data['Product']['slug'] = $this->Product->generateSlug($slug);
                        $this->data['Product']['hash'] = $this->__generateKey('Product');
                        $this->data['Product']['wisn'] = $this->__generateWisn('Product');
                        $this->data['Product']['status'] = 1;
                        $this->data['Product']['tax_type'] = 9;
                        $this->data['Product']['created_by'] = $this->Auth->User('id');
                        $this->data['Product']['fullfiled_by'] = "Admin";
                        //pr($this->data);
                        //exit;
                        $this->Product->Save($this->data['Product']);
                        $last_id = $this->Product->getLastInsertId();
                        if (isset($this->data['Product']['img']) and ($this->data['Product']['img'])) {
                            $this->data['Product']['id'] = $last_id;
                            $img_name = $this->url_upload('Product', $this->data['Product']['img']);
                            $this->data['Product']['img'] = $img_name;
                            $this->Product->Save($this->data['Product']);
                        }
                        if (isset($this->data['Product']['rel_img']) and ($this->data['Product']['rel_img'])) {
                            $exp_rel_images = explode('@@', $this->data['Product']['rel_img']);
                            //pr($exp_rel_images);
                            //exit;
                            //$last_id = 901; 
                            foreach ($exp_rel_images as $exp_rel_image) {

                                $img_name = $this->url_upload('Product/' . $last_id . '', $exp_rel_image);
                                $img_rel_arr[] = $img_name;
                            }
                            if (isset($img_rel_arr) and ($img_rel_arr)) {
                                $this->data['Product']['rel_img'] = implode(',', $img_rel_arr);
                                $this->data['Product']['id'] = $last_id;
                                $this->Product->Save($this->data['Product']);
                            }
                        }
                        $this->data['MasterProduct'] = $Productno['MasterProduct'];
                        if (isset($this->data['MasterProduct']) and ($this->data['MasterProduct'])) {
                            $this->data['MasterProduct']['id'] = "";
                            $this->data['MasterProduct']['user_id'] = $this->Auth->User('id');
                            $this->data['MasterProduct']['seller_id'] = $seller_id_1;
                            $this->data['MasterProduct']['product_id'] = $last_id;
                            $this->data['MasterProduct']['wisn'] = $this->data['Product']['wisn'];
                            $pr_weight = str_replace(' ', "", $this->data['Product']['weight']);
                            $pr_weight = str_replace('lb', "", $pr_weight);
                            $product_defined_wieght = $this->_get_seller_shipping_rate($pr_weight, $this->data['MasterProduct']['seller_id']
                            );
                            if (isset($product_defined_wieght) and ($product_defined_wieght)) {
                                if (isset($this->data['MasterProduct']['shipping_method']) and
                                        ($this->data['MasterProduct']['shipping_method'] == 'MSF')) {
                                    $this->data['MasterProduct']['shipping_price'] =
                                            ($this->data['Product']['weight'] * $product_defined_wieght);
                                } else {
                                    $this->data['MasterProduct']['shipping_price'] = 0;
                                }
                            } else {
                                $this->data['MasterProduct']['shipping_price'] = 0;
                            }
                            $this->MasterProduct->Save($this->data['MasterProduct']);
                        }
                    endif;
                    $no++;
                }
                $this->Session->setFlash('Your Inventory has been updated successfully.');
                $this->render('admin_adduploadproduct');
            } else {
                $this->Session->setFlash('Please upload products with correct CSV File Format.');
                $this->render('admin_adduploadproduct');
            }
        }
    }

    function admin_export() {
        echo __METHOD__;
        // SET LAYOUT
        $this->layout = 'ajax';
        $user_id = $this->Auth->User('id');
        $seller = $this->Seller->findByUserId($user_id, array('fields' => 'Seller.id'));
        $seller_id = $seller['Seller']['id'];
        // GRAB DATA
        $csv = NULL;
        // CSV HEADERS
        $csv .= 'Product ID';
        $csv .= ', Product Name';
        $csv .= ', Product WISN/ISBN';
        $csv .= ', Product Qty';
        $csv .= ', Product SKU';
        $csv .= ', Product created';
        $csv .= "\n";
        $csv = substr($csv, 0, -1) . "\n";
        // FEED IN DATA
        if (isset($seller_id) and ($seller_id)) {
            $seller_id = base64_decode($seller_id);
            $conditions = 'MasterProduct.seller_id="' . $seller_id . '"';
        } else {
            $conditions = "";
        }
        $merchants = $this->MasterProduct->find('all', array('fields' => 'DISTINCT MasterProduct.product_id', 'conditions' => '' . $conditions . ''));
        //pr($merchants);
        //exit;
        $x = 0;
        if (isset($merchants) and ($merchants)) {
            foreach ($merchants as $merchant) {
                $merchants = $this->MasterProduct->findByProductId($merchant['MasterProduct']['product_id']);

                $results = $this->Product->findById($merchant['MasterProduct']['product_id'], array('fields' => 'Product.id, Product.name, Product.wisn'));
                if (isset($results) and ($results)) {
                    $MuM[$x]['MasterProduct'] = $merchants['MasterProduct'];
                    $MuM[$x]['Product'] = $results['Product'];
                    $x++;
                }
            }
            if (isset($MuM) and ($MuM)) {
                foreach ($MuM as $result) {
                    $csv .= $result['Product']['id'];
                    $csv .= ', ' . $result['Product']['name'];
                    $csv .= ', ' . $result['Product']['wisn'];
                    $csv .= ', ' . $result['MasterProduct']['qty'];
                    $csv .= ', ' . $result['MasterProduct']['sku'];
                    $csv .= ', ' . $result['MasterProduct']['created'];
                    $csv .= "\n";
                }
            } else {
                $csv .= "Currently No Products History Available.";
                $csv .= "\n";
            }
        } else {
            $csv .= ", Currently No Products History Available.";
            $csv .= "\n";
        }

        // CREATE FILE AND INSTANTLY DOWNLOAD
        header("Content-type: application/vnd.ms-excel");
        header("Content-disposition: csv; filename=all_products" . date("Y-m-d") . ".csv; size=" . strlen($csv));
        echo $csv;
        exit;
    }

    function admin_add_brand($model ="", $enc_id="") {
        echo __METHOD__;
        $_list_categories = $this->_get_parent_categories();
        $x = 0;
        foreach ($_list_categories as $_list) {
            $_1_subcategories = $this->_get_subcatecategories($_list['Category']['id'], "");
            $_list_categories[$x]['Category']['Sub_1_Cat'] = $_1_subcategories;
            if (isset($_1_subcategories) and $_1_subcategories) {
                $x_1 = 0;
                foreach ($_1_subcategories as $_1_sub) {
                    $_2_subcategories = $this->_get_subcatecategories($_1_sub['Category']['id'], "");
                    if (isset($_2_subcategories) and $_2_subcategories) {
                        $_list_categories[$x]['Category']['Sub_1_Cat'][$x_1]['Category']['Sub_2_cat'][$x_1] = $_2_subcategories;
                    }
                    $x_1++;
                }
            }

            $x++;
        }
        if (isset($_list_categories) and $_list_categories) {
            $x_2 = 1;
            foreach ($_list_categories as $_list_categories) {
                $new_list_cat[$x_2] = $_list_categories;
                $x_2++;
            }
            ksort($new_list_cat);
            $this->Set('_list_categories', $new_list_cat);
        }

        if (isset($enc_id) and ($enc_id)) {
            $dec_id = base64_decode($enc_id);
            $details = $this->Brand->findById($dec_id);
            $this->Set('details', $details);
        }
        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['Brand']) and ($this->data['Brand'])) {
                // pr($this->data['Brand']);
                //exit;
                $this->data['Brand']['cat_id'] = implode(', ', $this->data['Brand']['cat_id']);
                $slug_string = str_replace('', '-', $this->data['Brand']['name']);
                $this->data['Brand']['slug'] = $this->Brand->generateSlug($slug_string);
                $this->Brand->Save($this->data['Brand']);
                if (isset($this->data['Brand']['id']) and ($this->data['Brand']['id'])) {
                    $last_id = $this->data['Brand']['id'];
                } else {
                    $last_id = $this->Brand->getLastInsertId();
                }
                if (isset($this->data['Brand']['imgImage']) and ($this->data['Brand']['imgImage'])
                        and ($this->data['Brand']['imgImage']['name'])) {
                    $image = $this->data['Brand']['imgImage'];
                    $this->data['Brand']['id'] = $last_id;
                    $Job_image_name = str_replace(' ', '_', $image['name']);
                    $job_image_name_explode = explode('.', $Job_image_name);
                    $job_image_name_explode_start_name = $job_image_name_explode[0];
                    $job_image_name_explode_ext = $job_image_name_explode[1];
                    $job_image_name_filtered = $last_id . "." . $job_image_name_explode_ext;
                    $this->data['Brand']['img'] = strtolower($job_image_name_filtered);
                    $image['name'] = $this->data['Brand']['img'];
                    $upload_file = $this->upload_img("", $image, 'Brand');
                    $this->Brand->save($this->data['Brand']);
                }
                $this->redirect(array('action' => 'admin_brands'));
            }
        }
    }

    function admin_get_option_values() {
        echo __METHOD__;
        $this->layout = "ajax";
        $params = $this->params;
        if (isset($params['form']['val']) and ($params['form']['val'] > 0)) {
            $option_values = $this->OptionValue->find('all', array('conditions' => 'OptionValue.option_id=' . $params['form']['val'] . ''));
            if (isset($option_values) and ($option_values)) {
                foreach ($option_values as $option_value) {
                    $list['' . $option_value['OptionValue']['id'] . ''] = $option_value['OptionValue']['value_name'];
                }
                $this->Set('list', $list);
            }
        }
    }

    function admin_products() {
        echo __METHOD__;
        $products = $this->Product->find('all');
        $this->Set('products', $products);
    }

    function admin_product_reviews() {
        echo __METHOD__;
        $this->paginate['ProductReview'] = array('conditions' => '',
            'limit' => 24,
            'fields' => array('ProductReview.*'),
            'order' => 'ProductReview.created Desc'
        );
        $ProductReviews = $this->paginate('ProductReview');
        if (isset($ProductReviews) and ($ProductReviews)) {
            $x = 0;
            foreach ($ProductReviews as $ProductReview) {
                $user = $this->User->findbyId($ProductReview['ProductReview']['user_id']);
                $ProductReviews[$x]['ProductReview']['user'] = $user['User'];
                $x++;
            }
            $this->Set('ProductReviews', $ProductReviews);
        }
    }

    function admin_update_status($model="", $table_id="", $status="", $return="") {
        echo __METHOD__;
        $this->data['' . $model . '']['status'] = $status;
        $this->data['' . $model . '']['id'] = $table_id;
        $this->$model->Save($this->data['' . $model . '']);
        $this->redirect(array('action' => $return));
    }

    function admin_get_attributes_values() {
        echo __METHOD__;
        $this->layout = "ajax";
        $params = $this->params;
        if (isset($params['form']['val']) and ($params['form']['val'])) {
            $subdivisions = $this->Attribute->find("all", array(
                'conditions' => 'Attribute.attr_gp_id="' . $params['form']['val'] . '"',
                'fields' => array('Attribute.id', 'Attribute.name', 'Attribute.required'
                ), 'limit' => ""));

            //pr($subdivisions);
            //exit;	
            $this->Set('_list_attributes', $subdivisions);
        } else {
            $this->Set('message', 'Please select other Attribute Group');
        }
    }

    function admin_add_product($model ="", $enc_id="") {
        echo __METHOD__;
        $__list_options = $this->__list_options();
        $this->Set('list_options', $__list_options);

        $_list_products = $this->_list_departments();
        $this->Set('list_products', $_list_products);

        $attrGroups = $this->__List_Group_attributes('');
        $this->Set('attrGroups', $attrGroups);


        if (isset($enc_id) and ($enc_id)) {
            $dec_id = base64_decode($enc_id);
            $details = $this->Product->findById($dec_id);
            /*             * ******************************************************************************** */
            /*
             * Specification Related to that Product
             */
            $specifications_attributes = $this->Specification->find('all', array(
                'conditions' => 'Specification.product_id="' . $details['Product']['id'] . '"',
                'fields' => 'DISTINCT Specification.attr_id'
                    ));
            //pr( $specifications_attributes );
            // exit;
            if (isset($specifications_attributes) and ( $specifications_attributes )) {

                foreach ($specifications_attributes as $specifications_attribute) {
                    $Attribute_GP_ID = $this->Attribute->find('first', array(
                        'conditions' => 'Attribute.id="' . $specifications_attribute['Specification']['attr_id'] . '"
																',
                        'fields' => 'Attribute.attr_gp_id'
                            ));
                    if (isset($Attribute_GP_ID) and ($Attribute_GP_ID)) {
                        $Gp_atr[] = $Attribute_GP_ID['Attribute']['attr_gp_id'];
                    }
                }
                $Gp_atr = array_unique($Gp_atr);
            }




            if (isset($Gp_atr) and ($Gp_atr)) {
                $v = 0;
                foreach ($Gp_atr as $Gp_at) {
                    $Gp_atr_1[$v] = $Gp_at;
                    $v++;
                }
                $x = 0;
                foreach ($Gp_atr_1 as $Gp_ID) {
                    $GRP_ATTR = $this->AttrGroup->findById($Gp_ID);
                    $Attributes = $this->Attribute->find('all', array(
                        'conditions' => 'Attribute.attr_gp_id="' . $Gp_ID . '"',
                        'fields' => 'Attribute.id'
                            ));

                    $o = 0;
                    foreach ($Attributes as $Attribute_id) {
                        $specifications = $this->Specification->find('all', array(
                            'conditions' => 'Specification.attr_id="' . $Attribute_id['Attribute']['id'] . '"',
                                ));
                        $specifications = array_unique($specifications);
                        if (isset($specifications) and ($specifications)):

                            foreach ($specifications as $specification) {
                                $xc = 0;
                                $attribute_key = $this->__get_attr_name($specification['Specification']['attr_id']);
                                $specifications[$xc]['Specification']['key'] = $attribute_key['Attribute']['name'];
                                $xc++;
                            }
                        endif;
                        unset($Attributes[$o]['Attribute']);
                        $Attributes[$o]['Specifications'] = $specifications;
                        $o++;
                    }
                    $Gp_atr_1[$x] = $GRP_ATTR;
                    $Gp_atr_1[$x]['AttrGroup']['Attributes'] = $Attributes;
                    $x++;
                }
                //pr($Gp_atr_1);
                //exit;
                $this->Set('Special_Specifications', $Gp_atr_1);
            }














            //pr($details);
            //exit;
            $this->Set('details', $details);
        }

        $_list_attributes = $this->_list_attributes('', 3);
        $this->Set('_list_attributes', $_list_attributes);

        $_list_stock_status = $this->_list_stock_status();
        $this->Set('list_stock_status', $_list_stock_status);


        //$_list_categories = $this->_list_categories();
        $_list_categories = $this->_list_categories();
        $cat_keys = array_keys($_list_categories);

        $x = 0;
        foreach ($cat_keys as $cat_id) {
            $cat_name = $this->Category->findById($cat_id, array('fields' => 'Category.name'));

            $_list_categori[$x]['subcatecategories'] = $this->_get_subcatecategories($cat_id);
            if (isset($_list_categori[$x]['subcatecategories']) and ($_list_categori[$x]['subcatecategories'])) {
                $_list_categori[$x]['name'] = $cat_name['Category']['name'];
            }
            $x++;
        }
        $this->Set('_list_categories', $_list_categori);
        $_list_brands = $this->_list_brands("", "");
        $this->Set('_list_brands', $_list_brands);

        if (isset($this->data) and ($this->data)) {
            //pr($this->data['Product']);
            //exit;
            if (isset($this->data['Product']) and ($this->data['Product'])) {
                $parent_cat = $this->__get_parent_id($this->data['Product']['cat_id'], "Category");
                $this->data['Product']['parent_cat_id'] = $parent_cat;
                $slug = str_replace(" ", "_", $this->data['Product']['name']);
                $slug = strtolower($slug);
                if (isset($this->data['Product']['id']) and ($this->data['Product']['id'])) {
                    if (isset($this->data['Product']['slug']) and ($this->data['Product']['slug'])) {
                        $slug = str_replace(" ", "_", $this->data['Product']['slug']);
                        $slug = strtolower($slug);
                        $this->data['Product']['slug'] = $slug;
                    }
                } else {
                    $this->data['Product']['slug'] = $this->Product->generateSlug($slug);
                }

                $this->data['Product']['wisn'] = $this->__generateWisn('Product');
                $this->data['Product']['hash'] = $this->__generateKey('Product');
                $this->data['Product']['created_by'] = $this->Auth->User('id');
                $this->data['Product']['weight'] = $this->data['Product']['weight'] . ' ' . $this->data['Product']['weight_unit'];
                $this->data['Product']['fullfiled_by'] = "Admin";
                $this->Product->Save($this->data['Product']);
                if (isset($this->data['Product']['id']) and ($this->data['Product']['id'])) {
                    $last_id = $this->data['Product']['id'];
                } else {
                    $last_id = $this->Product->getLastInsertId();
                }

                if (isset($this->data['Product']['Attr']) and ($this->data['Product']['Attr'])) {
                    foreach ($this->data['Product']['Attr'] as $attr) {
                        if (isset($attr['attr_value']) and ($attr['attr_value'])) {
                            if (isset($attr['id']) and ($attr['id'])) {
                                $this->data['Specification']['id'] = $attr['id'];
                            } else {
                                $this->data['Specification']['id'] = "";
                            }
                            $this->data['Specification']['key'] = $attr['key'];
                            $this->data['Specification']['attr_id'] = $attr['attribute'];
                            $this->data['Specification']['value'] = $attr['attr_value'];
                            $this->data['Specification']['product_id'] = $last_id;
                            $this->Specification->Save($this->data['Specification']);
                        }
                    }
                }
                if (isset($this->data['Product']['multi']) and ($this->data['Product']['multi'][0]['name']) and sizeof($this->data['Product']['multi'][0]['name'])) {
                    $this->data['Product']['id'] = $last_id;
                    $xo = 1;
                    foreach ($this->data['Product']['multi'] as $multiupload) {
                        if (isset($multiupload) and ($multiupload) and ($multiupload['name'])) {
                            $image = $multiupload;
                            $name = str_replace(' ', '_', $image['name']);
                            $nameex_explode = explode('.', $name);
                            $nameex = $nameex_explode[0];
                            $name_ext = $nameex_explode[1];
                            $filtered = $last_id . '' . ($xo * (date('ymd') . time())) . "." . $name_ext;
                            $image['name'] = strtolower($filtered);
                            $combined_name[] = $image['name'];
                            $upload_file = $this->upload_img($last_id, $image, 'Product');
                            $xo++;
                        }
                    }
                    $this->data['Product']['rel_img'] = implode(', ', $combined_name);
                    $this->Product->save($this->data['Product']);
                }
                if (isset($this->data['Product']['imgImage']) and ($this->data['Product']['imgImage'])
                        and ($this->data['Product']['imgImage']['name'])) {
                    $image = $this->data['Product']['imgImage'];
                    $this->data['Product']['id'] = $last_id;
                    $Job_image_name = str_replace(' ', '_', $image['name']);
                    $job_image_name_explode = explode('.', $Job_image_name);
                    $job_image_name_explode_start_name = $job_image_name_explode[0];
                    $job_image_name_explode_ext = $job_image_name_explode[1];
                    $job_image_name_filtered = date('ymd') . time() . $last_id . "." . $job_image_name_explode_ext;
                    $this->data['Product']['img'] = strtolower($job_image_name_filtered);
                    $image['name'] = strtolower($job_image_name_filtered);
                    ;
                    $upload_file = $this->upload_img("", $image, 'Product');
                    $this->Product->save($this->data['Product']);
                }
                if (isset($this->data['Product']['option']) and
                        ($this->data['Product']['option'][0]['option_id']) and
                        ($this->data['Product']['option']['product_option'][0]['value_name'])) {
                    if (isset($this->data['Product']['option']['product_option']) and ($this->data['Product']['option']['product_option']))
                        foreach ($this->data['Product']['option']['product_option'] as $product_option) {
                            if (isset($product_option['qty']) and ($product_option['qty'])) {
                                $this->data['OptionValue']['qty'] = $product_option['qty'];
                            } else {
                                $this->data['OptionValue']['qty'] = 1;
                            }
                            $this->data['OptionValue']['id'] = "";
                            $this->data['OptionValue']['option_id'] = $this->data['Product']['option'][0]['option_id'];
                            $this->data['OptionValue']['value_name'] = $product_option['value_name'];
                            $this->data['OptionValue']['subtract_stock'] = $product_option['subtract_stock'];
                            if (isset($product_option['price']) and ($product_option['price'])) {
                                $this->data['OptionValue']['price'] = $product_option['price'];
                            } else {
                                $this->data['OptionValue']['price'] = "";
                            }
                            if (isset($product_option['weight']) and ($product_option['weight'])) {
                                $this->data['OptionValue']['weight'] = $product_option['weight'];
                            } else {
                                $this->data['OptionValue']['weight'] = "";
                            }
                            $this->data['OptionValue']['product_id'] = $last_id;
                            $this->OptionValue->Save($this->data['OptionValue']);
                        }
                }

                /* if(isset($last_id) and ($last_id))
                  {
                  if(isset($this->data['MasterProduct']) and ($this->data['MasterProduct']))
                  {
                  $this->data['MasterProduct']['user_id']  =   $this->Auth->User('id');
                  $this->data['MasterProduct']['seller_id']  = 1;  // THis Seller Id for Wondere Default Seller Account
                  $this->data['MasterProduct']['product_id']  = $last_id ;
                  $this->data['MasterProduct']['wisn']  = $this->data['Product']['wisn'];
                  $this->data['MasterProduct']['price'] = $this->data['MasterProduct']['price'];
                  $this->data['MasterProduct']['qty'] = 1 ; //Default Qty enter by Wonder E admin
                  $this->data['MasterProduct']['conditions'] = 1 ; //  Dfault New Condition BY WonderE
                  $this->data['MasterProduct']['shipping_method'] = 'WSF' ;
                  $this->MasterProduct->Save($this->data['MasterProduct']);
                  }
                  } */
                $this->redirect(array('action' => 'admin_products'));
            }
        }
    }

    function admin_shippings() {
        echo __METHOD__;
        $this->paginate['Shipping'] = array('conditions' => '',
            'limit' => 10,
        );
        $Shippings = $this->paginate('Shipping');
        $this->Set('Shippings', $Shippings);
    }

    function admin_shippingsp() {
        echo __METHOD__;
        $this->paginate['ShippingSp'] = array('conditions' => '',
            'limit' => 10,
        );
        $ShippingSp = $this->paginate('ShippingSp');
        $this->Set('ShippingSps', $ShippingSp);
    }

    function admin_add_shipping() {
        echo __METHOD__;
        $countries = $this->__list_countries();
        $this->Set('countries', $countries);
        $sps = $this->__list_shipping_sps();
        $this->Set('sps', $sps);
        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['Shipping']) and ($this->data['Shipping'])) {
                $this->Shipping->Save($this->data['Shipping']);
                $this->redirect(array('action' => 'admin_shippings'));
            }
        }
    }

    function admin_get_attributes_cat() {
        echo __METHOD__;
        $this->layout = "ajax";
        $arribute_groups = $this->AttrGroup->find('all', array('conditions' => 'AttrGroup.cat_id=' . $_REQUEST['cat_id'] . '',
            'fields' => 'AttrGroup.id'));
        if (isset($arribute_groups) and ($arribute_groups)) {
            $x = 0;
            foreach ($arribute_groups as $Gp_ID) {
                $GRP_ATTR = $this->AttrGroup->findById($Gp_ID['AttrGroup']['id']);
                $Attributes = $this->Attribute->find('all', array(
                    'conditions' => 'Attribute.attr_gp_id="' . $Gp_ID['AttrGroup']['id'] . '"',
                    'fields' => 'Attribute.*'
                        ));


                $Gp_atr_1[$x] = $GRP_ATTR;
                $Gp_atr_1[$x]['AttrGroup']['Attributes'] = $Attributes;
                $x++;
            }
            //pr($Gp_atr_1);
            //exit;
            $this->Set('Special_Specifications', $Gp_atr_1);
        }
    }

    function admin_add_shippingSp() {
        echo __METHOD__;
        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['ShippingSp']) and ($this->data['ShippingSp'])) {
                $this->ShippingSp->Save($this->data['ShippingSp']);
                $this->redirect(array('action' => 'admin_shippingsp'));
            }
        }
    }

    /*
     * Feb 24 2012 End 
     */



    /*
     * Feb 27 2012 Start here 
     */

    function admin_coupons() {
        echo __METHOD__;
        $coupons = $this->Coupon->find('all');
        $this->Set('coupons', $coupons);
    }

    function admin_add_coupons($model="", $id="") {
        echo __METHOD__;
        if (isset($id) and ($id)) {
            $id_decr = base64_decode($id);
            $detail = $this->Coupon->findById($id_decr);
            $this->Set('details', $detail);
        } else {
            $detail = array();
            $this->Set('details', $detail);
        }
        $_list_categories = $this->_list_categories();
        $this->Set('categories', $_list_categories);

        $_list_products = $this->_list_products();
        $this->Set('list_products', $_list_products);


        if (isset($this->data['Coupon']) and ($this->data['Coupon'])) {
            //pr($this->data['Coupon']);
            //exit;

            if (isset($this->data['Coupon']['cat_id'])) {
                $cat_ides = implode(', ', $this->data['Coupon']['cat_id']);
                $this->data['Coupon']['cat_id'] = $cat_ides;

                //pr($this->data['Coupon']['cat_id']);
                //exit;
            }
            if (isset($this->data['Coupon']['products'])) {
                $products_ides = implode(', ', $this->data['Coupon']['products']);
                $this->data['Coupon']['products'] = $products_ides;
            }
            $this->Coupon->Save($this->data['Coupon']);
            $this->redirect(array('action' => 'admin_coupons'));
        }
    }

    function admin_gifts() {
        echo __METHOD__;
        $Gift = $this->Gift->find('all');
        $this->Set('Gifts', $Gift);
    }

    function admin_add_gift($model="", $id="") {
        echo __METHOD__;
        if (isset($id) and ($id)) {
            $id_decr = base64_decode($id);
            $detail = $this->Gift->findById($id_decr);
            $this->Set('details', $detail);
        } else {
            $detail = array();
            $this->Set('details', $detail);
        }
        if (isset($this->data['Gift']) and ($this->data['Gift'])) {
            $this->Gift->Save($this->data['Gift']);
            $this->redirect(array('action' => 'admin_gifts'));
        }
    }

    /*
     * Feb 27 2012 End  here 
     */

    function admin_cities() {
        echo __METHOD__;
        $this->paginate['City'] = array('conditions' => '',
            'limit' => 10,
        );
        $Cities = $this->paginate('City');
        $this->Set('Cities', $Cities);
    }

    function admin_shipping_service_providers() {
        echo __METHOD__;
        $this->paginate['ShippingSp'] = array('conditions' => '',
            'limit' => 10,
        );
        $ShippingSps = $this->paginate('ShippingSp');
        $this->Set('ShippingSp', $ShippingSps);
    }

    function admin_categories($parent_cat_slug="") {
        echo __METHOD__;
        if (isset($parent_cat_slug) and ($parent_cat_slug)) {
            $cat_id = $this->__get_slug_to__id($parent_cat_slug, 'Category');
            $cond = "Category.pid=" . $cat_id . "";
        } else {
            $cond = "";
        }

        $this->paginate['Category'] = array('conditions' => $cond,
            'limit' => 200,
            'order' => 'Category.id Desc',
        );
        $Categories = $this->paginate('Category');

        if (isset($Categories) and ($Categories)) {

            $x = 0;
            foreach ($Categories as $Categoy) {
                $parent_cat_result = $this->_get_parent_cat($Categoy['Category']['id']);
                $Categories[$x]['Category']['ParentType'] = $parent_cat_result;
                $x++;
            }
        }
        $this->Set('Category', $Categories);
    }

    function admin_departments() {
        echo __METHOD__;
        $this->paginate['Department'] = array('conditions' => '',
            'limit' => 200,
            'order' => 'Department.id Desc',
        );
        $Departments = $this->paginate('Department');
        if (isset($Departments) and ($Departments)) {
            $x = 0;
            foreach ($Departments as $dept) {
                $cat = $this->__get_details($dept['Department']['cat_id'], 'Category');
                $Departments[$x]['Department']['Cat_name'] = $cat['Category']['name'];
                $x++;
            }

            $this->Set('Departments', $Departments);
        }
    }

    function admin_adddepartment($model ="", $enc_id="") {
        echo __METHOD__;
        $_list_categories = $this->_list_categories();
        $_list_categories[0] = 'Parent';
        ksort($_list_categories);
        $this->Set('_list_categories', $_list_categories);
        if (isset($enc_id) and ($enc_id)) {
            $dec_id = base64_decode($enc_id);
            $details = $this->Department->findById($dec_id);
            $this->Set('details', $details);
        }
        if (isset($this->data) and ($this->data['Department'])) {
            $slug = str_replace(" ", "_", $this->data['Department']['name']);
            $slug = strtolower($slug);
            $this->data['Department']['cat_id'] = implode(', ', $this->data['Department']['cat_id']);
            $this->data['Department']['slug'] = $this->Department->generateSlug($slug);
            $this->Department->Save($this->data['Department']);
            $this->redirect(array('controller' => 'Setups', 'action' => 'departments'));
        }
    }

    /*
     * Edit User
     */

    function admin_edit_user($slug="") {
        echo __METHOD__;
        $user_details = $this->User->findBySlug($slug);
        if (isset($user_details) and ($user_details)) {
            $this->set('details', $user_details);
        }

        if (empty($this->data) == false) {
            if ($this->data) {
                //pr($this->data);
                //exit;
                if (isset($this->data['User']) and ($this->data['User'])) {
                    if (isset($this->data['User']['imgImage']) and ($this->data['User']['imgImage']) and ($this->data['User']['imgImage']['name'])) {
                        $Startup_id = $this->data['User']['id'];
                        $image = $this->data['User']['imgImage'];
                        $Job_image_name = str_replace(' ', '_', $image['name']);
                        $job_image_name_explode = explode('.', $Job_image_name);
                        $job_image_name_explode_start_name = $job_image_name_explode[0];
                        $job_image_name_explode_ext = $job_image_name_explode[1];
                        $job_image_name_filtered = date("d-m-Y") . "_" . $Startup_id .
                                "_" . substr($job_image_name_explode_start_name, 0, 5) . "." . $job_image_name_explode_ext;
                        $this->data['User']['img'] = strtolower($job_image_name_filtered);
                        $image['name'] = $this->data['User']['img'];
                        $upload_file = $this->upload_img('', $image, 'User');
                    }
                    $this->User->Save($this->data['User']);
                }
                $this->Session->setFlash('Data Has been Successfully Saved.');
                $this->redirect(array('controller' => 'Setups', 'action' => 'admin_users_list'));
            }
        }
    }

    function admin_addcategory($model ="", $enc_id="") {
        echo __METHOD__;
        if (isset($enc_id) and ($enc_id)) {
            $dec_id = base64_decode($enc_id);

            $details = $this->Category->findById($dec_id);
            $this->Set('details', $details);
        }

        $_list_categories = $this->_get_parent_categories();
        $x = 0;
        foreach ($_list_categories as $_list) {
            $_1_subcategories = $this->_get_subcatecategories($_list['Category']['id'], "");
            $_list_categories[$x]['Category']['Sub_1_Cat'] = $_1_subcategories;
            if (isset($_1_subcategories) and $_1_subcategories) {
                $x_1 = 0;
                foreach ($_1_subcategories as $_1_sub) {
                    $_2_subcategories = $this->_get_subcatecategories($_1_sub['Category']['id'], "");
                    if (isset($_2_subcategories) and $_2_subcategories) {
                        $_list_categories[$x]['Category']['Sub_1_Cat'][$x_1]['Category']['Sub_2_cat'][$x_1] = $_2_subcategories;
                    }
                    $x_1++;
                }
            }

            $x++;
        }
        if (isset($_list_categories) and $_list_categories) {
            $x_2 = 1;
            foreach ($_list_categories as $_list_categories) {
                $new_list_cat[$x_2] = $_list_categories;
                $x_2++;
            }
            //$new_list_cat[0] ='Parent';
            ksort($new_list_cat);
            //pr($new_list_cat);
            //exit;
            $this->Set('_list_categories', $new_list_cat);
        }

        if (isset($this->data) and ($this->data)) {
            //pr($this->data);
            //exit;
            if ($this->data['Category']) {

                if (!$this->data['Category']['id']) {
                    $this->data['Category']['slug'] =
                            $this->Category->generateSlug(str_replace(' ', '_', strtolower($this->data['Category']['name'])));
                }
                $this->Category->Save($this->data['Category']);
                if (isset($this->data['Category']['id']) and ($this->data['Category']['id'])) {
                    $last_id = $this->data['Category']['id'];
                } else {
                    $last_id = $this->Category->getLastInsertId();
                }
                if (isset($this->data['Category']['imgImage']) and ($this->data['Category']['imgImage'])
                        and ($this->data['Category']['imgImage']['name'])) {
                    $image = $this->data['Category']['imgImage'];
                    $this->data['Category']['id'] = $last_id;
                    $Job_image_name = str_replace(' ', '_', $image['name']);
                    $job_image_name_explode = explode('.', $Job_image_name);
                    $job_image_name_explode_start_name = $job_image_name_explode[0];
                    $job_image_name_explode_ext = $job_image_name_explode[1];
                    $job_image_name_filtered = $last_id . "." . $job_image_name_explode_ext;
                    $this->data['Category']['img'] = strtolower($job_image_name_filtered);
                    $image['name'] = $this->data['Category']['img'];
                    $upload_file = $this->upload_img("", $image, 'Category');
                    $this->Category->save($this->data['Category']);
                } else {
                    //echo "hi";
                    if ($this->data['Category']['imgvalue'] != 'hi') {
                        ///echo "in if";
                        $this->data['Category']['id'] = $last_id;
                        $this->data['Category']['img'] = "";
                        //pr($this->data['Category']); 
                        $this->Category->Save($this->data['Category']);
                    }
                }
                $this->redirect(array('action' => 'admin_categories'));
            }
        }
    }

    function admin_add_city() {
        echo __METHOD__;
        $_list_states = $this->_list_states();
        $this->Set('list_states', $_list_states);

        if (isset($this->data) and ($this->data)) {
            if ($this->data['City']) {
                $this->data['City']['slug'] = $this->City->generateSlug(str_replace(' ', '_', strtolower($this->data['City']['name'])));
                $this->City->Save($this->data['City']);
                $this->redirect(array('action' => 'admin_cities'));
            }
        }
    }

    function admin_add_State() {
        echo __METHOD__;
        if (isset($this->data) and ($this->data)) {
            if ($this->data['State']) {
                $this->State->Save($this->data['State']);
                $this->redirect(array('action' => 'admin_states'));
            }
        }
    }

    /*     * ********************************************************************************************************************************** */

    /*
     * Delete Multiple  User
     */

    function admin_delete_multiple_user() {
        echo __METHOD__;
        if ((empty($this->data['checksel']) == false)) {
            $selected_list = $this->data['checksel'];
            $selected_list = array_keys($selected_list);
            foreach ($selected_list as $selected_list) {
                if ($selected_list !== 0) {
                    $this->User->query('delete from users where id = "' . $selected_list . '"');
                }
            }
            $this->Session->setFlash('Selected Users Has been Deleted.');
            $this->redirect(array('controller' => 'setups', 'action' => 'admin_users_list',));
        } else if (isset($this->data['checksel']) == "") {
            $this->Session->setFlash('Please Select atleast one User.');
            $this->redirect(array('controller' => 'setups', 'action' => 'admin_users_list',));
        }
    }

    /*     * ********************************************************************************************************************************** */

    /*
     * Menu Creation
     */

    function admin_menu() {
        echo __METHOD__;
        $this->layout = "admin";
        $published = array('1' => 'Yes', '0' => 'No');
        $this->set('published', $published);
        if (empty($this->data['Menu']) == false) {
            if ($this->data['Menu']) {
                $this->Menu->save($this->data['Menu']);
                $this->Session->setFlash('Menu Has been Created.');
                $this->redirect(array('controller' => 'setups', 'action' => 'admin_menu_list',));
            } else {
                $this->Session->setFlash('Please Entred Sutable Value in Fields..');
                $this->redirect(array('controller' => 'setups', 'action' => 'admin_menu',));
            }
        }
    }

    function admin_menu_list() {
        echo __METHOD__;
        $this->layout = "admin";
        $menu_list = $this->paginate('Menu');
        $this->set('menu_list', $menu_list);
    }

    function admin_pages_list() {
        echo __METHOD__;
        $page_list = $this->paginate('Page');
        $this->set('page_list', $page_list);
    }

    function admin_page_create() {
        echo __METHOD__;
        $this->layout = "admin";
        if (empty($this->data['Page']) == false) {
            if ($this->data['Page']) {
                $page_title = strtolower($this->data['Page']['page_title']);
                //$slug_value=str_replace(' ','-',$slug_value);
                $slug_value = $this->Page->generateSlug($page_title);
                $this->data['Page']['slug'] = $slug_value;
                $this->data['Page']['created_by'] = $this->Session->read('User.id');
                $this->data['Page']['modified_by'] = $this->Session->read('User.id');
                $this->Page->save($this->data['Page']);
                $this->Session->setFlash('Page Has been Created.');
                $this->redirect(array('controller' => 'setups', 'action' => 'admin_pages_list',));
            } else {
                $this->Session->setFlash('Please Enter the Correct values.');
                $this->redirect(array('controller' => 'setups', 'action' => 'admin_pages_list',));
            }
        }
    }

    function admin_page_edit($page_slug) {
        echo __METHOD__;
        $this->layout = "admin";
        $page_id = $this->__get_slug_to__id($page_slug, "Page");
        $page_details = $this->__get_details($page_id, "Page");
        $this->set('page_details', $page_details);
        if (empty($this->data['Page']) == false) {
            if ($this->data['Page']) {
                $slug_value = strtolower($this->data['Page']['slug']);
                $slug_value = str_replace(' ', '-', $slug_value);
                if ($this->data['Page']['slug'] == $page_details['Page']['slug']) {
                    $this->data['Page']['slug'] = $page_details['Page']['slug'];
                } else {
                    $this->data['Page']['slug'] = $slug_value;
                }
                //$this->data['Page']['modified_by']=$this->Session->read('User.id');
                $this->Page->save($this->data['Page']);
                $this->Session->setFlash('Page Has been Updated.');
                $this->redirect(array('controller' => 'setups', 'action' => 'admin_pages_list',));
            } else {
                $this->Session->setFlash('Please Enter the Correct values.');
                $this->redirect(array('controller' => 'setups', 'action' => 'admin_pages_list',));
            }
        } else {
            $page_details = $this->__get_details($page_id, "Page");
            $this->set('page_details', $page_details);
        }
    }

    function admin_edit_menu($id="") {
        echo __METHOD__;
        $this->layout = "admin";
        $published = array('1' => 'Yes', '0' => 'No');
        $this->set('published', $published);
        $menu_details = $this->_menu_details($id);
        $this->set('menu_details', $menu_details);
        if (empty($this->data['Menu']) == false) {
            if ($this->data['Menu']) {
                $this->Menu->save($this->data['Menu']);
                $this->Session->setFlash('Menu Has been Updated.');
                $this->redirect(array('controller' => 'setups', 'action' => 'admin_menu_list'));
            } else {
                $this->Session->setFlash('Please Entred Sutable Value in Fields..');
                $this->redirect(array('controller' => 'setups', 'action' => 'admin_menu_list'));
            }
        }
    }

    /*     * ********************************************************************************************************************************** */
    /*
     * Delete Single Menu
     */

    function admin_delete_menu($id) {
        echo __METHOD__;
        if ($this->Menu->delete($id)) {
            $this->Session->setFlash('The Menu has been deleted.');
            $this->redirect(array('action' => 'admin_menu_list', 'controller' => 'setups'));
        }
    }

    /*     * ********************************************************************************************************************************** */



    /*
     * Create Sub  Menu
     */

    function _list_submenus() {
        echo __METHOD__;
        $subdivisions = $this->MenuItem->find("all", array('MenuItem' => '', 'fields' => array('MenuItem.id', 'MenuItem.item_title')));
        $result = Set::combine($subdivisions, '{n}.MenuItem.id', '{n}.MenuItem.item_title');
        return $result;
    }

    function admin_menu_item_create($selected_menu_id = null) {
        echo __METHOD__;
        $this->layout = "admin";
        $menu_list = $this->__menu_list();
        $i = 0;
        $menu_select = array();
        foreach ($menu_list as $menu) {
            $menu_id = $menu['Menu']['id'];
            $menu_title = $menu['Menu']['menu_title'];
            $menu_select[$menu_id] = $menu_title;
            $i++;
        }
        $this->set('menu_list', $menu_select);
        $sub_menu_list = $this->_list_submenus();
        $sub_menu_list['0'] = 'Parent';
        ksort($sub_menu_list);
        $this->set('sub_menu_list', $sub_menu_list);

        $menu_item_types = array('1' => 'CMS PAGE');
        $this->set('menu_item_types', $menu_item_types);

        $pages_list = $this->_list_pages();
        $this->set('pages_list', $pages_list);

        $published = array('1' => 'Yes', '0' => 'No');
        $this->set('published', $published);

        if (empty($this->data['MenuItem']) == false) {
            if ($this->data['MenuItem']) {
                if ($this->data['MenuItem']['parent_id'] == 'parent_id') {
                    $this->data['MenuItem']['parent_id'] = 0;
                } else {
                    $this->data['MenuItem']['parent_id'] = $this->data['MenuItem']['parent_id'];
                }
                $this->MenuItem->save($this->data['MenuItem']);
                $this->Session->setFlash('Menu Item Has been Created.');
                $this->redirect(array('controller' => 'setups', 'action' => 'admin_sub_menu_list',));
            }
        }
        $this->set('selected_menu_id', $selected_menu_id);
    }

    function admin_menu_item_edit($item_id) {
        echo __METHOD__;
        $this->layout = "admin";
        $menu_list = $this->__menu_list();
        $i = 0;
        $menu_select = array();
        foreach ($menu_list as $menu) {
            $menu_id = $menu['Menu']['id'];
            $menu_title = $menu['Menu']['menu_title'];
            $menu_select[$menu_id] = $menu_title;
            $i++;
        }
        $this->set('menu_list', $menu_select);

        $sub_menu_list = $this->_list_submenus();
        $sub_menu_list['0'] = 'Parent';
        ksort($sub_menu_list);
        $this->set('sub_menu_list', $sub_menu_list);

        $menu_item_types = array('1' => 'CMS PAGE');
        $this->set('menu_item_types', $menu_item_types);

        $pages_list = $this->_list_pages();
        $this->set('pages_list', $pages_list);

        $published = array('1' => 'Yes', '0' => 'No');
        $this->set('published', $published);

        $menu_item = $this->_details_menu_item($item_id);
        $this->set('menu_item', $menu_item);
        if (empty($this->data['MenuItem']) == false) {
            if ($this->data['MenuItem']) {
                if ($this->data['MenuItem']['parent_id'] == 'parent_id') {
                    $this->data['MenuItem']['parent_id'] = 0;
                } else {
                    $this->data['MenuItem']['parent_id'] = $this->data['MenuItem']['parent_id'];
                }
                $this->MenuItem->save($this->data['MenuItem']);
                $this->Session->setFlash('Menu Item Has been updated.');
                $this->redirect(array('controller' => 'setups', 'action' => 'menu_list'));
            }
        }
    }

    function admin_sub_menu_list($main_menu_id = null) {
        echo __METHOD__;
        $this->layout = "admin";
        if (isset($main_menu_id) and $main_menu_id) {
            $sub_menu_list = $this->MenuItem->find('all', array('conditions' => 'MenuItem.menu_id="' . $main_menu_id . '"'));
        } else {
            $sub_menu_list = $this->MenuItem->find('all');
        }

        /*
          $this->paginate['MenuItem'] = $sub_menu_list;
          $sub_menu_list = $this->paginate('MenuItem'); */

        $i = 0;
        foreach ($sub_menu_list as $menu_item) {
            $menu_name = $this->_menu_name($menu_item['MenuItem']['menu_id']);
            $parent_type = $this->_parent_item_name($menu_item['MenuItem']['parent_id']);
            $sub_menu_list[$i]['menu_name'] = $menu_name;
            $sub_menu_list[$i]['parent_type'] = $parent_type;
            $i++;
        }
        $this->set('sub_menu_list', $sub_menu_list);
        $this->set('main_menu_id', $main_menu_id);
    }

    /*
     * Delete Single Menu
     */

    function admin_delete_sub_menu($id) {
        echo __METHOD__;
        if ($this->MenuItem->delete($id)) {
            $this->Session->setFlash('The menu_item has been deleted.');
            $this->redirect(array('action' => 'admin_sub_menu_list', 'controller' => 'setups'));
        }
    }

    /*
     * Delete Multiple  Menu
     */

    function admin_delete_multiple_sub_menu() {
        echo __METHOD__;
        if (empty($this->data['checksel']) == false) {
            $selected_list = $this->data['checksel'];
            //pr($selected_list);
            //exit;
            foreach ($selected_list as $selected_list) {
                if ($selected_list !== 0) {
                    $this->MenuItem->query('delete from menu_items where id = "' . $selected_list . '"');
                }
            }
            $this->Session->setFlash('Selected Menu items has been Deleted.');
            $this->redirect(array('controller' => 'setups', 'action' => 'admin_sub_menu_list',));
        } else if (isset($this->data['checksel']) == "") {
            $this->Session->setFlash('Please Select atleast one Sub Menu Item.');
            $this->redirect(array('controller' => 'setups', 'action' => 'admin_sub_menu_list',));
        }
    }

    function __send_mail($mail_persons_list, $mail_subject, $mail_message, $mail_from_email = "", $mail_from_name = "") {

        echo __METHOD__;
        //echo "<br>Mail Persons new array: ";
        //$mail_persons = array();
        //$mail_persons['manish.dreamweb@gmail.com'] = 'Manish Kumar';
        //pr($mail_persons);

        App::import('Vendor', 'lib/swift_required');
        //App::import('Vendors', 'WellNamed', array('file' => 'services'.DS.'well.named.php'));

        $transport = Swift_SmtpTransport::newInstance('localhost', 25);
        $mailer = Swift_Mailer::newInstance($transport);
        if (!$mail_from_email) {
            //Take mail from from email config
            $mail_from_email = Configure::read('Website.from_email');
        }

        if (!$mail_from_name) {
            //Take mail from from name config
            $mail_from_name = Configure::read('Website.from_name');
        }

        $message = Swift_Message::newInstance('' . $mail_subject . '')
                ->setFrom(array('' . $mail_from_email . '' => '' . $mail_from_name . ''))
                ->setTo($mail_persons_list)
                ->setBody('' . $mail_message . '', 'text/html')
                ->addPart('' . $mail_message . '', 'text/plain');
        ;

        //Send the message
        $result = $mailer->send($message);
        //exit;

        if ($result) {
            //$this->Session->setFlash('Your Mail has been Sent.');
            //$this->redirect(array('action' => 'view_projects','controller'=>'projects'));
        }
    }

    function admin_delete_multiple() {
        echo __METHOD__;
        if (empty($this->data['checksel']) == false) {
            $selected_list = $this->data['checksel'];

            $table_name = $this->data['table_name'];

            $model = $this->data['model'];

            $action = $this->data['action'];


            foreach ($selected_list as $selected_list) {
                if ($selected_list !== 0) {
                    $this->$model->query('delete from ' . $table_name . ' where id = "' . $selected_list . '"');
                }
            }
            $this->Session->setFlash('' . $model . ' Items has been Deleted.');
            $this->redirect(array('controller' => 'setups', 'action' => $action));
        } else if (isset($this->data['checksel']) == "") {
            $this->Session->setFlash('Please Select atleast one ' . $model . '.');
            $this->redirect(array('controller' => 'setups', 'action' => 'admin_orders_list',));
        }
    }

    /*     * ***************************************************************************************************************************************** */

    /*
     * Function defined for supplementry.com
     */

    /*
      / Add Category
     */

    function admin_addcategory_2($slug="") {
        echo __METHOD__;
        if (isset($slug) and sizeof($slug)) {
            $model = "Category";

            $cat_id = $this->__get_slug_to__id($slug, $model);

            $cat_details = $this->__get_detils($cat_id, $model);

            if (isset($cat_details) and sizeof($cat_details)) {
                $cat_details = $cat_details;
            } else {
                $cat_details = "";
            }

            $this->Set('cat_details', $cat_details);

            $categories = $this->_list_categories();

            $categories[0] = 'Parent';

            $this->Set('categories', $categories);
        } else {
            $categories = $this->_list_categories();

            $categories[0] = 'Parent';

            $this->Set('categories', $categories);
        }

        if (isset($this->data) and sizeof($this->data)) {
            if (isset($this->data['Category'])) {
                if (isset($this->data['Category']['id']) and (!empty($this->data['Category']['id']))) {
                    $slud_filter = str_replace(' ', '-', strtolower($this->data['Category']['slug']));

                    $Category_Slug = $this->Category->generateSlug($slud_filter);

                    $this->data['Category']['slug'] = $Category_Slug;
                } else {
                    $slud_filter = str_replace(' ', '-', strtolower($this->data['Category']['categoryName']));

                    $Category_Slug = $this->Category->generateSlug($slud_filter);

                    $this->data['Category']['slug'] = $Category_Slug;

                    $this->data['Category']['hash'] = $this->__generateKey_Category();
                }

                $this->Category->Save($this->data['Category']);

                if (isset($this->data['Category']['id']) and $this->data['Category']['id']) {
                    $Category_insert_id = $this->data['Category']['id'];
                } else {
                    $Category_insert_id = $this->Category->getLastInsertId();
                }
                if (isset($this->data['Category']['image']) and sizeof($this->data['Category']['image']) and (!empty($this->data['Category']['image']['name']))) {
                    //echo "image block";

                    $Category_image_name = str_replace(' ', '_', $this->data['Category']['image']['name']);

                    $Category_image_name_explode = explode('.', $Category_image_name);

                    $Category_image_name_explode_start_name = $Category_image_name_explode[0];

                    $Category_image_name_explode_ext = $Category_image_name_explode[1];

                    $Category_image_name_filtered = date("dmYhis") . "_" . $Category_insert_id . "_" . substr($Category_image_name_explode_start_name, 0, 5) . "." . $Category_image_name_explode_ext;

                    $this->data['Category']['image']['name'] = strtolower($Category_image_name_filtered);

                    $this->data['Category']['img'] = $this->data['Category']['image']['name'];

                    $upload_file = $this->upload_img($Category_insert_id, $this->data['Category']['image'], 'Category');

                    $this->data['Category']['id'] = $Category_insert_id;

                    $this->Category->Save($this->data['Category']);
                }

                if (isset($this->data['Category']['id'])) {
                    //exit;
                    $this->Session->setFlash('Category has been Updated');
                    $this->redirect(array('action' => 'addcategory'));
                } else {
                    $this->Session->setFlash('Category has been added');
                    $this->redirect(array('action' => 'addcategory'));
                }
            } else {
                $this->Session->setFlash('Please Enter a valid data');

                $this->redirect(array('action' => 'addcategory'));
            }
        }
    }

    /*     * ************************************************************************************************************************************************* */

    function admin_managecategory() {
        echo __METHOD__;
        isset($this->data['Category']) ? $sort = $this->data['Category'] : $sort = "id ASC";
        $categories = $this->_get_parent_categories(5, $sort);
        $this->Set('categories', $categories);
    }

    /*
     * Manage Subcategories
     */

    function admin_Subcategories($slug="") {
        echo __METHOD__;
        $this->layout = "admin";
        $cat_id = $this->__get_slug_to__id($slug, 'Category');
        $cat_details = $this->__get_detils($cat_id, 'Category');
        $this->set('cat_details', $cat_details);
        $Subcategories = $this->_get_admin_Subcategories($slug, 5);
        $this->Set('Subcategories', $Subcategories);
    }

    function admin_get_sub_categories() {
        echo __METHOD__;
        if (($this->Session->read('User.is_admin')) == 1) {
            $this->layout = "ajax";
            $params = $this->params;
            if (isset($params['url']['id']) and !empty($params['url']['id'])) {
                $cat_id = $params['url']['id'];
                $sub_cats = $this->_list_Sub_categories($cat_id);
                if (isset($sub_cats) and sizeof($sub_cats)) {
                    $sub_cats = $sub_cats;
                    $this->Set('sub_cats', $sub_cats);
                } else {
                    $no_sub_cats = 'NO Subcategory';
                    $this->Set('no_sub_cats', $no_sub_cats);
                }
            } else {
                $no_sub_cats = 'Please Select Exact Category.';
                $this->Set('no_sub_cats', $no_sub_cats);
            }
        }
    }

    /*
     * ------------------------------------------------------RANJEET Retailers Section ------------------------------------------------------------------*
     */

    function admin_add_retailers($slug="") {
        echo __METHOD__;
        if (isset($slug) and sizeof($slug)) {
            $model = "Retailer";

            $cat_id = $this->__get_slug_to__id($slug, $model);

            $Retailer_details = $this->__get_detils($cat_id, $model);

            if (isset($Retailer_details) and sizeof($Retailer_details)) {
                $Retailer_details = $Retailer_details;
            } else {
                $Retailer_details = "";
            }



            $this->Set('Retailer_details', $Retailer_details);

            $countries = $this->_list_countries();

            $this->Set('countries', $countries);
        } else {
            $countries = $this->_list_countries();

            $this->Set('countries', $countries);
        }

        if (isset($this->data) and sizeof($this->data)) {
            if (isset($this->data['Retailer'])) {
                if (isset($this->data['Retailer']['id']) and (!empty($this->data['Retailer']['id']))) {
                    if ($this->data['Retailer']['slug'] == $this->data['Retailer']['old_slug']) {
                        $this->data['Retailer']['slug'] = $this->data['Retailer']['old_slug'];
                    } else {
                        $slud_filter = str_replace(' ', '-', strtolower($this->data['Retailer']['slug']));

                        $Retailer_Slug = $this->Retailer->generateSlug($slud_filter);

                        $this->data['Retailer']['slug'] = $Retailer_Slug;
                    }
                } else {
                    $slud_filter = str_replace(' ', '-', strtolower($this->data['Retailer']['Retailer_name']));

                    $Retailer_Slug = $this->Retailer->generateSlug($slud_filter);

                    $this->data['Retailer']['slug'] = $Retailer_Slug;

                    $this->data['Retailer']['hash'] = $this->__generateKey_all('Retailer');
                }
                $this->data['Retailer']['countries'] = implode(',', $this->data['Retailer']['countries']);
                $this->Retailer->Save($this->data['Retailer']);

                if (isset($this->data['Retailer']['id']) and $this->data['Retailer']['id']) {
                    $Retailer_insert_id = $this->data['Retailer']['id'];
                } else {
                    $Retailer_insert_id = $this->Retailer->getLastInsertId();
                }
                if (isset($this->data['Retailer']['image']) and sizeof($this->data['Retailer']['image']) and (!empty($this->data['Retailer']['image']['name']))) {
                    $Retailer_image_name = str_replace(' ', '_', $this->data['Retailer']['image']['name']);
                    $Retailer_image_name_explode = explode('.', $Retailer_image_name);
                    $Retailer_image_name_explode_start_name = $Retailer_image_name_explode[0];
                    $Retailer_image_name_explode_ext = $Retailer_image_name_explode[1];
                    $Retailer_image_name_filtered = date("dmYhis") . "_" . $Retailer_insert_id . "_" . substr($Retailer_image_name_explode_start_name, 0, 5) . "." . $Retailer_image_name_explode_ext;

                    $this->data['Retailer']['image']['name'] = strtolower($Retailer_image_name_filtered);

                    $this->data['Retailer']['img'] = $this->data['Retailer']['image']['name'];

                    $upload_file = $this->upload_img($Retailer_insert_id, $this->data['Retailer']['image'], 'Retailer');

                    $this->data['Retailer']['id'] = $Retailer_insert_id;

                    $this->Retailer->Save($this->data['Retailer']);
                }

                if (isset($this->data['Retailer']['id'])) {
                    //exit;
                    $this->Session->setFlash('Retailer has been Updated');
                    $this->redirect(array('action' => 'add_retailers'));
                } else {
                    $this->Session->setFlash('Retailer has been added');
                    $this->redirect(array('action' => 'add_retailers'));
                }
            } else {
                $this->Session->setFlash('Please Enter a valid data');

                $this->redirect(array('action' => 'add_retailers'));
            }
        }
    }

    /*
     * Delete the specific Table item
     */

    function admin_delete($model, $slug, $action) {
        echo __METHOD__;
        $id = $this->__get_slug_to__id($slug, $model);
        //exit;
        if ($this->$model->delete($id)) {
            $this->Session->setFlash('The ' . $model . ' item has been deleted.');

            $this->redirect(array('action' => $action, 'controller' => 'setups'));
        }
    }

    /*
     * Delete the specific Table item
     */

    function admin_delete_by_id($model, $id, $action) {
        echo __METHOD__;
        if ($this->$model->delete($id)) {
            $this->Session->setFlash('The ' . $model . ' item has been deleted.');

            $this->redirect(array('action' => $action, 'controller' => 'setups'));
        }
    }

    function admin_ups_shippings() {
        echo __METHOD__;
        $custum_settings = $this->UpsShipping->findById(1);
        $this->Set('custum_settings', $custum_settings);
        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['UpsShipping']) and ($this->data['UpsShipping'])) {
                $this->data['UpsShipping']['id'] = 1;
                $this->data['UpsShipping']['services'] = implode(',', $this->data['UpsShipping']['services']);
                $this->data['UpsShipping']['dimentions'] = implode('*', $this->data['UpsShipping']['dimentions']);
                $this->UpsShipping->Save($this->data['UpsShipping']);
                $this->redirect(array('action' => 'admin_ups_shippings', 'controller' => 'setups'));
            }
        }
    }

    function admin_fedex_shippings() {
        echo __METHOD__;
        $custum_settings = $this->FedexShipping->findById(1);
        $this->Set('custum_settings', $custum_settings);
        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['FedexShipping']) and ($this->data['FedexShipping'])) {
                $this->data['FedexShipping']['id'] = 1;
                $this->data['FedexShipping']['services'] = implode(',', $this->data['FedexShipping']['services']);
                $this->data['FedexShipping']['dimentions'] = implode('*', $this->data['FedexShipping']['dimentions']);
                $this->FedexShipping->Save($this->data['FedexShipping']);
                $this->redirect(array('action' => 'admin_fedex_shippings', 'controller' => 'setups'));
            }
        }
    }

    function admin_flate_shippings() {
        echo __METHOD__;
        $custum_settings = $this->FlateRate->findById(1);
        $this->Set('custum_settings', $custum_settings);
        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['FlateRate']) and ($this->data['FlateRate'])) {
                $this->data['FlateRate']['id'] = 1;
                $this->FlateRate->Save($this->data['FlateRate']);
                $this->redirect(array('action' => 'admin_flate_shippings', 'controller' => 'setups'));
            }
        }
    }

}

